package cn.qicaiwang.open.app.mapper;

import cn.qicaiwang.open.app.entity.UserMembership;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 用户会员Mapper接口
 */
public interface UserMembershipMapper {
    /**
     * 创建用户会员
     * @param membership 用户会员实体
     * @return 影响行数
     */
    @Insert("INSERT INTO user_membership(user_id, plan_id, start_time, end_time, " +
            "total_api_calls, remaining_api_calls, status) " +
            "VALUES(#{userId}, #{planId}, #{startTime}, #{endTime}, " +
            "#{totalApiCalls}, #{remainingApiCalls}, #{status})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(UserMembership membership);

    /**
     * 更新用户会员
     * @param membership 用户会员实体
     * @return 影响行数
     */
    @Update("UPDATE user_membership SET user_id=#{userId}, plan_id=#{planId}, " +
            "start_time=#{startTime}, end_time=#{endTime}, " +
            "total_api_calls=#{totalApiCalls}, remaining_api_calls=#{remainingApiCalls}, " +
            "status=#{status} WHERE id=#{id}")
    int update(UserMembership membership);

    /**
     * 根据ID查询用户会员
     * @param id 用户会员ID
     * @return 用户会员实体
     */
    @Select("SELECT * FROM user_membership WHERE id=#{id}")
    UserMembership selectById(Long id);

    /**
     * 根据用户ID查询用户会员
     * @param userId 用户ID
     * @return 用户会员列表
     */
    @Select("SELECT * FROM user_membership WHERE user_id=#{userId}")
    List<UserMembership> selectByUserId(Long userId);

    /**
     * 根据用户ID和状态查询用户会员
     * @param userId 用户ID
     * @param status 状态
     * @return 用户会员实体
     */
    @Select("SELECT * FROM user_membership WHERE user_id=#{userId} AND status=#{status}")
    UserMembership selectByUserIdAndStatus(@Param("userId") Long userId, @Param("status") Boolean status);

    /**
     * 根据状态查询用户会员
     * @param status 状态
     * @return 用户会员列表
     */
    @Select("SELECT * FROM user_membership WHERE status=#{status}")
    List<UserMembership> selectByStatus(Boolean status);

    /**
     * 扣除API调用次数
     * @param userId 用户ID
     * @param cost 扣除数量
     * @return 影响行数
     */
    @Update("UPDATE user_membership SET remaining_api_calls = remaining_api_calls - #{cost} " +
            "WHERE user_id=#{userId} AND status=1 AND remaining_api_calls >= #{cost}")
    int deductApiCalls(@Param("userId") Long userId, @Param("cost") int cost);
}

